package site.xuqing.socketbus.uitls;

import android.os.Environment;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author xuqing
 * @Description 端口管理工具类，如果没有内存卡，无法保存端口，则无法跨进程通讯
 * @createTime 2022年01月24日 13:27:46
 */
public class PortUtil {
    public static final String ROOT_PATH = "/SocketBus/";
    public static int DEFAULT_PORT = 52090;
    
    public static void setPort(int port) {
        try {
            String diskPath = getDiskCacheDir();
            if (diskPath == null) {
                DEFAULT_PORT = port;
            } else {
                String portPath = diskPath + ROOT_PATH;
                File file = new File(portPath);
                if (!file.exists()) {
                    file.mkdirs();
                }
                File portFile = new File(portPath, "port");
                FileOutputStream outputStream = new FileOutputStream(portFile);
                String portStr = String.valueOf(port);
                outputStream.write(portStr.getBytes());
                outputStream.flush();
                outputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public static int getPort() {
        try {
            String diskPath = getDiskCacheDir();
            if (diskPath == null) {
                return DEFAULT_PORT;
            } else {
                File portFile=new File(diskPath+ROOT_PATH,"port");
                if (portFile.exists()){
                    FileInputStream inputStream=new FileInputStream(portFile);
                    StringBuilder sb=new StringBuilder();
                    int tempPort;
                    while ((tempPort=inputStream.read())!=-1){
                        sb.append((char) tempPort);
                    }
                    inputStream.close();
                    return Integer.parseInt(sb.toString());
                }else{
                    return -1;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return -1;
    }
    
    public static String getDiskCacheDir() {
        String cachePath = null;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
            || !Environment.isExternalStorageRemovable()) {
            cachePath = Environment.getExternalStorageDirectory().getPath();
        }
        return cachePath;
    }
    
}
